﻿<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑供应商</title>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/element-plus/dist/index.css">
    <script src="https://unpkg.com/element-plus"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 20px 0;
            background-color: #f5f7fa;
            min-height: 100vh;
            box-sizing: border-box;
        }

        .container {
            padding: 0 20px;
            max-width: 1200px;
            margin: 0 auto;
            width: 100%;
            box-sizing: border-box;
        }

        .form-section {
            background: #fff;
            padding: 25px;
            margin-bottom: 20px;
            border-radius: 6px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        }

            .form-section h3 {
                margin-top: 0;
                margin-bottom: 20px;
                color: #333;
                font-size: 16px;
                border-left: 3px solid #409eff;
                padding-left: 10px;
                font-weight: 500;
            }

        .el-row {
            margin-bottom: 18px;
        }

        .saveBlock {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: #fff;
            padding: 15px 20px;
            border-top: 1px solid #eee;
            z-index: 999;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.03);
        }

        .btnBlock {
            text-align: right;
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            box-sizing: border-box;
        }

        .required-mark {
            color: #f56c6c;
            margin-right: 4px;
        }

        .error-tip {
            color: #f56c6c;
            font-size: 12px;
            margin-top: 5px;
        }

        .attachment-item {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            padding: 8px;
            background: #f8f9fa;
            border-radius: 4px;
        }

        .current-value {
            color: #67c23a;
            font-size: 12px;
            margin-top: 5px;
        }

        @@media (max-width: 768px) {
            .container {
                padding: 0 15px;
            }

            .form-section {
                padding: 15px;
            }
        }
    </style>
</head>
<body>
    <div id="app" class="container">
        <!-- 基础信息表单 -->
        <div class="form-section">
            <h3>基础信息</h3>
            <el-form ref="basicForm" :model="formData" :rules="basicRules" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="供应商编码" prop="supplierCode">
                            <el-input v-model="formData.supplierCode" placeholder="自动生成" disabled></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="供应商名称" prop="supplierName">
                            <el-input v-model.trim="formData.supplierName" placeholder="请输入供应商名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="所属行业" prop="industry">
                            <el-select v-model="formData.industry" placeholder="请选择" clearable>
                                <el-option v-for="item in industryList" :key="item.code" :label="item.name" :value="Number(item.code)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="供应商分类" prop="customerSource">
                            <el-select v-model="formData.customerSource" placeholder="请选择" clearable>
                                <el-option v-for="item in typeList" :key="item.code" :label="item.name" :value="Number(item.code)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="联系人" prop="contactPerson">
                            <el-input v-model="formData.contactPerson" placeholder="请输入联系人姓名"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" prop="contactPhone">
                            <el-input v-model="formData.contactPhone" placeholder="请输入联系电话"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="电子邮箱" prop="email">
                            <el-input v-model="formData.email" placeholder="请输入电子邮箱"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="*进货部门" prop="customerId">
                            <el-select v-model="formData.customerId" placeholder="请选择部门" clearable>
                                <el-option v-for="dept in deptList" :key="dept.id" :label="dept.name" :value="Number(dept.id)"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="*进货负责人" prop="purchaseManagerId">
                            <el-select v-model="formData.purchaseManagerId" placeholder="请选择负责人" clearable>
                                <el-option v-for="user in allUserList" :key="user.id" :label="user.name" :value="Number(user.id)"></el-option>
                            </el-select>
                            <div class="current-value" v-if="formData.purchaseManagerId">
                                当前负责人: {{ getCurrentManagerName() }}
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="*状态" prop="status">
                            <el-radio-group v-model="formData.status">
                                <el-radio v-for="item in statusList" :key="item.code" :label="item.code" border>
                                    {{ item.name }}
                                </el-radio>
                            </el-radio-group>
                            <div class="current-value" v-if="formData.status">
                                当前状态: {{ getCurrentStatusName() }}
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="供应商地址" prop="address">
                            <el-input v-model="formData.address" placeholder="请输入供应商详细地址"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remarks">
                            <el-input v-model="formData.remarks" type="textarea" rows="3" placeholder="请输入备注信息"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 财务信息表单 -->
        <div class="form-section">
            <h3>财务信息</h3>
            <el-form ref="financeForm" :model="formData" :rules="financeRules" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="账户名称" prop="accountName">
                            <el-input v-model="formData.accountName" placeholder="请输入开户账户名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="纳税人识别号" prop="taxpayerId">
                            <el-input v-model="formData.taxpayerId" placeholder="请输入18位纳税人识别号"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="银行账号" prop="bankAccount">
                            <el-input v-model="formData.bankAccount" placeholder="请输入银行账号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开户银行" prop="openingBank">
                            <el-input v-model="formData.openingBank" placeholder="请输入开户银行名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="银行地址" prop="bankAddress">
                            <el-input v-model="formData.bankAddress" placeholder="请输入开户行详细地址"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 附件上传 -->
        <div class="form-section">
            <h3>上传附件</h3>
            <el-upload ref="upload"
                       v-model:file-list="fileList"
                       action="/api/upload/attachment"
                       :auto-upload="true"
                       :on-success="handleUploadSuccess"
                       :on-error="handleUploadError"
                       :on-change="handleFileChange"
                       :limit="5"
                       :file-list="existingAttachments"
                       accept=".doc,.docx,.pdf,.rar,.zip,.jpg,.png"
                       list-type="text">
                <el-button type="primary" :loading="uploadLoading">选择文件</el-button>
                <div class="el-upload__text">
                    支持 doc、pdf、rar、zip、jpg、png 等格式，单个文件最大200MB
                </div>
            </el-upload>
            <div v-if="existingAttachments.length > 0" style="margin-top: 15px;">
                <h4>已上传附件</h4>
                <div v-for="file in existingAttachments" :key="file.uid" class="attachment-item">
                    <el-link :href="file.url" target="_blank" type="primary">{{ file.name }}</el-link>
                    <el-button type="text" @@click="handleRemoveAttachment(file)" style="margin-left: 10px;">删除</el-button>
                </div>
            </div>
        </div>

        <!-- 按钮栏 -->
        <div class="saveBlock">
            <div class="btnBlock">
                <el-button @@click="handleClose" :loading="buttonLoading.close">关闭</el-button>
                &nbsp;&nbsp;
                <el-button type="primary" @@click="handleSaveDraft" :loading="buttonLoading.saveDraft">保存草稿</el-button>
                &nbsp;&nbsp;
                <el-button type="success" @@click="handleUpdate" :loading="buttonLoading.update">保存修改</el-button>
            </div>
        </div>
    </div>

    <script>
        const { createApp, ref, reactive, onMounted, toRaw, computed } = Vue;
        const { ElMessage, ElMessageBox } = ElementPlus;

        createApp({
            setup() {
                // 获取URL中的供应商ID
                const getSupplierIdFromUrl = () => {
                    const urlParams = new URLSearchParams(window.location.search);
                    const id = urlParams.get('id') || urlParams.get('supplierId');
                    const validId = id ? Number(id) : null;
                    return validId && validId > 0 ? validId : null;
                };

                const supplierId = getSupplierIdFromUrl();
                const rawSupplierData = ref(null);

                // 表单数据
                const formData = reactive({
                    supplierId: supplierId,
                    supplierCode: '',
                    supplierName: '',
                    industry: null,
                    customerSource: null,
                    contactPerson: '',
                    contactPhone: '',
                    email: '',
                    customerId: null,
                    purchaseManagerId: null,
                    status: '1',
                    address: '',
                    remarks: '',
                    accountName: '',
                    taxpayerId: '',
                    bankAccount: '',
                    openingBank: '',
                    bankAddress: '',
                    attachmentId: 0
                });

                // 附件相关
                const fileList = ref([]);
                const existingAttachments = ref([]);
                const uploadLoading = ref(false);

                // 核心数据
                const industryList = ref([]);
                const typeList = ref([]);
                const deptList = ref([]);
                const userList = ref([]);
                const statusList = ref([]);

                // 计算属性：显示所有用户
                const allUserList = computed(() => {
                    return userList.value;
                });

                // 表单引用
                const basicForm = ref(null);
                const financeForm = ref(null);

                // 按钮加载状态
                const buttonLoading = reactive({
                    close: false,
                    saveDraft: false,
                    update: false
                });

                // 基础表单验证规则
                const basicRules = {
                    supplierName: [{ required: true, message: '请输入供应商名称', trigger: ['blur', 'change'] }],
                    customerId: [{ required: true, message: '请选择进货部门', trigger: ['blur', 'change'] }],
                    purchaseManagerId: [{ required: true, message: '请选择进货负责人', trigger: ['blur', 'change'] }],
                    status: [{ required: true, message: '请选择状态', trigger: ['blur', 'change'] }]
                };

                // 财务表单验证规则
                const financeRules = {
                    taxpayerId: [{ pattern: /^\d{18}$/, message: '纳税人识别号为18位数字', trigger: 'blur', required: false }]
                };

                // 获取当前状态名称
                const getCurrentStatusName = () => {
                    if (!formData.status) return '未知状态';
                    const statusCode = formData.status.toString();
                    if (statusCode === '0') return '启用';
                    if (statusCode === '1') return '停用';
                    const status = statusList.value.find(item => item.code.toString() === statusCode);
                    return status ? status.name : `未知状态(${statusCode})`;
                };

                // 加载字典数据
                const loadDictData = async () => {
                    try {
                        const [industryRes, typeRes, statusRes] = await Promise.all([
                            axios.get('/BiSupplier/GetDictData?type=supplier_industry'),
                            axios.get('/BiSupplier/GetDictData?type=supplier_type'),
                            axios.get('/BiSupplier/GetDictData?type=supplier_status')
                        ]);

                        industryList.value = industryRes.data.data || [];
                        typeList.value = typeRes.data.data || [];
                        statusList.value = statusRes.data.data || [];
                    } catch (error) {
                        console.error('字典数据加载失败:', error);
                        ElMessage.error(`字典数据加载异常：${error.message}`);
                    }
                };

                // 获取当前负责人名称
                const getCurrentManagerName = () => {
                    if (!formData.purchaseManagerId) return '未选择';
                    const user = userList.value.find(u => u.id === formData.purchaseManagerId);
                    return user ? user.name : '未知用户';
                };

                // 加载部门和用户数据
                const loadDeptAndUser = async () => {
                    try {
                        const [deptRes, userRes] = await Promise.all([
                            axios.get('/BiSupplier/GetOrgTree'),
                            axios.get('/BiSupplier/GetUsers')
                        ]);

                        // 处理部门数据
                        const flattenDeptList = (treeNodes) => {
                            const result = [];
                            const flatten = (nodes) => {
                                if (!nodes || !Array.isArray(nodes)) return;
                                nodes.forEach(node => {
                                    if (node) {
                                        result.push({
                                            id: node.id || node.orgId || node.value,
                                            name: node.label || node.orgName || node.name
                                        });
                                        if (node.children && node.children.length > 0) {
                                            flatten(node.children);
                                        }
                                    }
                                });
                            };
                            flatten(deptRes.data.data || []);
                            return result;
                        };

                        deptList.value = flattenDeptList(deptRes.data.data || []);
                        userList.value = userRes.data.data || [];
                    } catch (error) {
                        console.error('部门用户数据加载失败:', error);
                        ElMessage.error(`部门/用户数据加载异常：${error.message}`);
                    }
                };

                // 加载供应商数据
                const loadSupplierData = async () => {
                    if (!supplierId) {
                        ElMessage.error('无效的供应商ID');
                        return;
                    }

                    try {
                        const res = await axios.post('/BiSupplier/Details', null, {
                            params: { id: supplierId }
                        });

                        if (res.data.code === 200 && res.data.data) {
                            const data = res.data.data;
                            rawSupplierData.value = data;

                            // 完整字段映射
                            formData.supplierId = data.supplierId || supplierId;
                            formData.supplierCode = data.supplierCode || '';
                            formData.supplierName = data.supplierName || '';

                            // 状态值处理
                            let statusValue = '1';
                            if (data.status !== undefined && data.status !== null) {
                                const dbStatus = data.status.toString();
                                if (dbStatus === '0') {
                                    statusValue = '1';
                                } else if (dbStatus === '1') {
                                    statusValue = '0';
                                }
                            }
                            formData.status = statusValue;

                            // 数字字段处理
                            formData.industry = data.industry != null ? Number(data.industry) : null;
                            formData.customerSource = data.customerSource != null ? Number(data.customerSource) : null;
                            formData.customerId = data.customerId != null ? Number(data.customerId) : null;

                            // 进货负责人
                            let purchaseManagerValue = null;
                            if (data.purchaseManagerId !== undefined && data.purchaseManagerId !== null) {
                                purchaseManagerValue = Number(data.purchaseManagerId);
                            }
                            formData.purchaseManagerId = purchaseManagerValue;

                            // 地址字段
                            formData.address = data.address || data.Address || '';

                            // 其他字段
                            formData.contactPerson = data.contactPerson || '';
                            formData.contactPhone = data.contactPhone || '';
                            formData.email = data.email || '';
                            formData.remarks = data.remarks || '';
                            formData.accountName = data.accountName || '';
                            formData.taxpayerId = data.taxpayerId || '';
                            formData.bankAccount = data.bankAccount || '';
                            formData.openingBank = data.openingBank || '';
                            formData.bankAddress = data.bankAddress || '';
                            formData.attachmentId = data.attachmentId || 0;

                            // 加载附件信息
                            await loadAttachmentInfo();

                            ElMessage.success('供应商数据加载成功');
                        } else {
                            ElMessage.error(res.data.msg || '数据加载失败');
                        }
                    } catch (error) {
                        console.error('供应商数据加载失败:', error);
                        ElMessage.error(`数据加载异常：${error.message}`);
                    }
                };

                // 加载附件信息
                const loadAttachmentInfo = async () => {
                    try {
                        if (formData.attachmentId > 0) {
                            existingAttachments.value = [
                                {
                                    uid: 1,
                                    name: '供应商合同.pdf',
                                    url: '/attachments/supplier_contract.pdf'
                                },
                                {
                                    uid: 2,
                                    name: '营业执照.jpg',
                                    url: '/attachments/business_license.jpg'
                                }
                            ];
                        }
                    } catch (error) {
                        console.warn('附件信息加载失败:', error);
                    }
                };

                // 附件上传成功处理
                const handleUploadSuccess = (response, file, fileList) => {
                    uploadLoading.value = false;
                    if (response.code === 200) {
                        ElMessage.success('文件上传成功');
                        formData.attachmentId = response.data.attachmentId;
                    } else {
                        ElMessage.error(response.msg || '文件上传失败');
                    }
                };

                // 附件上传失败处理
                const handleUploadError = (error, file, fileList) => {
                    uploadLoading.value = false;
                    ElMessage.error('文件上传失败: ' + error.message);
                };

                // 文件选择处理
                const handleFileChange = (file, files) => {
                    if (file.size > 200 * 1024 * 1024) {
                        ElMessage.error('文件大小不能超过200MB');
                        fileList.value = files.filter(f => f.uid !== file.uid);
                        return;
                    }
                    uploadLoading.value = true;
                };

                // 删除附件
                const handleRemoveAttachment = (file) => {
                    ElMessageBox.confirm('确定要删除这个附件吗？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        existingAttachments.value = existingAttachments.value.filter(item => item.uid !== file.uid);
                        ElMessage.success('附件删除成功');
                    });
                };

                // 关闭按钮
                const handleClose = () => {
                    buttonLoading.close = true;
                    window.history.back();
                };

                // 保存草稿
                const handleSaveDraft = async () => {
                    try {
                        buttonLoading.saveDraft = true;

                        const draftData = {
                            formData: toRaw(formData),
                            fileList: fileList.value,
                            existingAttachments: existingAttachments.value,
                            saveTime: new Date().toLocaleString()
                        };
                        localStorage.setItem(`supplierDraft_${supplierId}`, JSON.stringify(draftData));

                        ElMessage.success('草稿保存成功！');
                    } catch (error) {
                        ElMessage.error('保存草稿失败，请重试');
                    } finally {
                        buttonLoading.saveDraft = false;
                    }
                };

                // 保存修改
                const handleUpdate = async () => {
                    try {
                        // 验证表单
                        const basicValid = await basicForm.value.validate();
                        const financeValid = await financeForm.value.validate();

                        if (!basicValid || !financeValid) {
                            ElMessage.warning('请完善表单信息');
                            return;
                        }

                        buttonLoading.update = true;

                        // 状态值处理
                        const frontendStatus = formData.status;
                        let backendStatus = frontendStatus;
                        if (frontendStatus === '0') {
                            backendStatus = '1';
                        } else if (frontendStatus === '1') {
                            backendStatus = '0';
                        }

                        // 构建提交数据
                        const submitData = {
                            SupplierId: formData.supplierId,
                            SupplierCode: formData.supplierCode,
                            SupplierName: formData.supplierName.trim(),
                            Industry: formData.industry ? Number(formData.industry) : 1,
                            CustomerSource: formData.customerSource ? Number(formData.customerSource) : 1,
                            ContactPerson: formData.contactPerson || "",
                            ContactPhone: formData.contactPhone || "",
                            Email: formData.email || "",
                            CustomerId: formData.customerId ? Number(formData.customerId) : null,
                            PurchaseManagerId: formData.purchaseManagerId ? Number(formData.purchaseManagerId) : null,
                            Status: backendStatus,
                            AccountName: formData.accountName || "",
                            TaxpayerId: formData.taxpayerId || "",
                            BankAccount: formData.bankAccount || "",
                            OpeningBank: formData.openingBank || "",
                            BankAddress: formData.bankAddress || "",
                            Remarks: formData.remarks || "",
                            AttachmentId: formData.attachmentId || 0,
                            Address: formData.address || "",
                            CreateBy: rawSupplierData.value?.createBy || "system",
                            CreateTime: rawSupplierData.value?.createTime || new Date().toISOString(),
                            UpdateBy: "system",
                            UpdateTime: new Date().toISOString(),
                            IsDelete: rawSupplierData.value?.isDelete || "0"
                        };

                        const res = await axios.post('/BiSupplier/Edit', submitData, {
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            params: { id: formData.supplierId }
                        });

                        if (res.data.code === 200) {
                            ElMessage.success('更新成功！');
                            localStorage.removeItem(`supplierDraft_${supplierId}`);
                            setTimeout(() => {
                                window.history.back();
                            }, 1000);
                        } else {
                            ElMessage.error(res.data.msg || '更新失败');
                        }
                    } catch (error) {
                        console.error('更新失败:', error);
                        if (error.response) {
                            ElMessage.error(error.response.data.msg || '请求失败');
                        } else if (error.request) {
                            ElMessage.error('网络错误，请检查网络连接');
                        } else {
                            ElMessage.error(`请求配置错误: ${error.message}`);
                        }
                    } finally {
                        buttonLoading.update = false;
                    }
                };

                // 页面初始化
                onMounted(async () => {
                    if (!supplierId) {
                        ElMessage.error('无效的供应商ID');
                        return;
                    }

                    try {
                        // 并行加载所有基础数据
                        await Promise.all([
                            loadDictData(),
                            loadDeptAndUser()
                        ]);

                        // 最后加载供应商详情数据
                        await loadSupplierData();

                        // 检查草稿数据
                        const draftKey = `supplierDraft_${supplierId}`;
                        const localDraft = localStorage.getItem(draftKey);
                        if (localDraft) {
                            ElMessageBox.confirm('检测到有保存的草稿数据，是否加载？', '提示', {
                                confirmButtonText: '加载草稿',
                                cancelButtonText: '使用服务器数据',
                                type: 'info'
                            }).then(() => {
                                const draft = JSON.parse(localDraft);
                                Object.assign(formData, draft.formData);
                                fileList.value = draft.fileList || [];
                                existingAttachments.value = draft.existingAttachments || [];
                                ElMessage.success('草稿数据加载成功');
                            }).catch(() => {
                                ElMessage.info('使用服务器数据');
                            });
                        }

                        // 清除验证状态
                        setTimeout(() => {
                            if (basicForm.value) basicForm.value.clearValidate();
                            if (financeForm.value) financeForm.value.clearValidate();
                        }, 1000);

                    } catch (error) {
                        console.error('页面加载失败:', error);
                        ElMessage.error('页面加载失败，请刷新重试');
                    }
                });

                return {
                    formData,
                    fileList,
                    existingAttachments,
                    uploadLoading,
                    industryList,
                    typeList,
                    deptList,
                    userList,
                    statusList,
                    allUserList,
                    basicForm,
                    financeForm,
                    buttonLoading,
                    basicRules,
                    financeRules,
                    getCurrentStatusName,
                    getCurrentManagerName,
                    handleClose,
                    handleSaveDraft,
                    handleUpdate,
                    handleFileChange,
                    handleUploadSuccess,
                    handleUploadError,
                    handleRemoveAttachment
                };
            }
        }).use(ElementPlus).mount('#app');
    </script>
</body>
</html>